package com.dfbz.多线程版在线聊天;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        //与服务器端请求连接
        Socket socket = new Socket("192.168.2.237", 8888);
        try {
            Thread.sleep(1000);
            System.out.println("请输入消息,按ENTER发送");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));//接收数据写入高效缓冲流。
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(outputStream));

        //线程1:读服务器发过来的消息
        new Thread() {
            @Override
            public void run() {
                try {
                    while (true) {
                        String msg = br.readLine();//读一整行的消息
                        if(msg.equals("88")){
                            System.out.println("聊天结束......");
                            try {
                                Thread.sleep(1000);
                                System.out.println("用户已下线......");
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.exit(0);//
                            break;
                        }else {
                            System.out.println("来自服务器的消息:"+msg);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        //线程2:向服务器发送信息
        new Thread() {
            @Override
            public void run() {
                try {
                while (true) {
                    String msg = new Scanner(System.in).nextLine();
                    //向服务器发送消息
                    bw.write(msg);
                    //写完换行
                    bw.newLine();
                    bw.flush();
                }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        }.start();
    }
}
